
// 草稿管理模块
const EmailDraftManager = {
    // 草稿相关数据
    draft: {
        current: null,
        saveInterval: null,
        statusUpdateInterval: null,
        lastSaveTime: null,
        attachments: [],
        contentChanged: false,
        lastContent: {
            to: '',
            cc: '',
            subject: '',
            body: ''
        },
        debounceTimer: null
    },

    // 打开撰写邮件弹窗
    openComposeModal: async function(options = {}) {
        const { title = '写邮件', to = '', cc = '', subject = '', body = '', draftId = null } = options;
        
        // 检查系统中是否有邮箱账号（使用缓存）
        let accounts = EmailModule.cache.accounts;
        if (!accounts || accounts.length === 0) {
            layui.layer.msg('请先添加邮箱账号', { icon: 7 });
            return;
        }
        
        // 检查是否选中了邮箱账号
        if (!EmailModule.cache.currentAccount) {
            layui.layer.msg('请先选择一个邮箱账号', { icon: 7 });
            return;
        }
        
        // 从缓存中获取当前账号信息
        let accountName = '';
        const currentAccount = EmailModule.cache.accounts.find(acc => acc.id === EmailModule.cache.currentAccount);
        if (currentAccount) {
            accountName = currentAccount.name || currentAccount.email;
        } else {
            accountName = '未知账号';
        }
        
        // 记录是否从草稿箱打开
        const isFromDraftFolder = EmailModule.cache.currentFolder === 'Drafts';
        
        this.draft.current = draftId;
        this.draft.lastSaveTime = null;
        this.draft.attachments = [];

        // 重置表单
        $('#compose-email-modal form')[0].reset();
        $('#compose-subject').val(subject);
        $('#draft-save-status').text('');
        $('#attachment-list').empty();
        
        // 清空并初始化邮箱徽标容器
        this.initEmailTagsInput('compose-to', to);
        this.initEmailTagsInput('compose-cc', cc);

        // 使用统一的设备检测决定弹窗尺寸
        let layerArea;
        
        if (DeviceDetector.isMobile() || DeviceDetector.isTablet()) {
            layerArea = ['100%', '100%'];
        } else {
            layerArea = ['1000px', '600px'];
        }
        
        layer.open({
            type: 1,
            title: `${title} - ${accountName}`,
            area: layerArea,
            content: $('#compose-email-modal'),
            maxmin: true,
            shadeClose: true,
            btn: ['立即发送', '重置'],
            btnAlign: 'c',
            yes: function(index, layero) {
                const form = $('#compose-email-modal form');
                const to = form.find('#compose-to').val();
                const cc = form.find('#compose-cc').val();
                const subject = form.find('#compose-subject').val();
                const body = editor.txt.html();

                if (!to || !subject) {
                    layui.layer.msg('收件人和主题不能为空');
                    return;
                }

                EmailDraftManager.sendEmail({
                    to, 
                    cc, 
                    subject, 
                    body, 
                    draft_id: EmailDraftManager.draft.current 
                });
                layer.close(index);
            },
            btn2: function(index, layero) {
                $('#compose-email-modal form')[0].reset();
                editor.txt.html('');
                return false;
            },
            success: function(layero, index) {
                if (editor) {
                    editor.destroy();
                    editor = null;
                }
                const E = window.wangEditor;
                editor = new E('#compose-body-editor');

                // 配置图片上传
                editor.config.uploadImgServer = `${Api.config.apiBaseUrl}/upload?type=image&account_id=${EmailModule.cache.currentAccount}`;
                editor.config.uploadFileName = 'file';
                editor.config.uploadImgHeaders = {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                };
                editor.config.uploadImgHooks = {
                    customInsert: function(insertImg, result, editor) {
                        if (result.success && result.data.url) {
                            insertImg(result.data.url);
                        } else {
                            layer.msg(result.msg || '上传失败');
                        }
                    }
                };

                editor.create();
                editor.txt.html(body);

                // 在工具栏末尾添加保存状态显示
                setTimeout(() => {
                    const toolbar = $('.w-e-toolbar');
                    if (toolbar.length) {
                        toolbar.append(`
                            <div id="editor-save-status" style="
                                display: inline-block;
                                color: #999;
                                font-size: 12px;
                                line-height: 40px;
                                padding: 0 10px;
                                margin-left: auto;
                            "></div>
                        `);
                    }
                }, 100);

                // 初始化上次保存的内容
                EmailDraftManager.draft.lastContent = {
                    to: to,
                    cc: cc,
                    subject: subject,
                    body: body
                };
                EmailDraftManager.draft.contentChanged = false;

                // 监听表单内容变化
                $('#compose-to, #compose-cc, #compose-subject').on('change', function() {
                    EmailDraftManager.checkContentChanged();
                    if (EmailDraftManager.draft.contentChanged) {
                        EmailDraftManager.saveDraftAuto();
                    }
                });

                // 监听编辑器内容变化 - 使用防抖机制
                editor.config.onchange = function(newHtml) {
                    EmailDraftManager.checkContentChanged();
                    if (EmailDraftManager.draft.debounceTimer) {
                        clearTimeout(EmailDraftManager.draft.debounceTimer);
                    }
                    EmailDraftManager.draft.debounceTimer = setTimeout(() => {
                        if (EmailDraftManager.draft.contentChanged) {
                            EmailDraftManager.saveDraftAuto();
                        }
                    }, 2000);
                };

                // 初始化附件上传
                EmailDraftManager.initAttachmentUpload();

                // 启动定时保存检查
                if (EmailDraftManager.draft.saveInterval) {
                    clearInterval(EmailDraftManager.draft.saveInterval);
                }
                EmailDraftManager.draft.saveInterval = setInterval(() => {
                    EmailDraftManager.saveDraftPeriodically();
                }, 1000);

                // 启动状态更新定时器
                if (EmailDraftManager.draft.statusUpdateInterval) {
                    clearInterval(EmailDraftManager.draft.statusUpdateInterval);
                }
                EmailDraftManager.draft.statusUpdateInterval = setInterval(() => {
                    EmailDraftManager.updateDraftSaveStatus();
                }, 1000);
            },
            end: function() {
                // 停止自动保存
                if (EmailDraftManager.draft.saveInterval) {
                    clearInterval(EmailDraftManager.draft.saveInterval);
                    EmailDraftManager.draft.saveInterval = null;
                }
                if (EmailDraftManager.draft.statusUpdateInterval) {
                    clearInterval(EmailDraftManager.draft.statusUpdateInterval);
                    EmailDraftManager.draft.statusUpdateInterval = null;
                }
                if (EmailDraftManager.draft.debounceTimer) {
                    clearTimeout(EmailDraftManager.draft.debounceTimer);
                    EmailDraftManager.draft.debounceTimer = null;
                }
                
                if (isFromDraftFolder) {
                    EmailListManager.reloadEmailList();
                }
                
                EmailDraftManager.draft.current = null;
                EmailDraftManager.draft.lastSaveTime = null;

                if (editor) {
                    editor.destroy();
                    editor = null;
                }
                EmailDraftManager.draft.attachments = [];
            }
        });
    },

    // 初始化附件上传功能
    initAttachmentUpload: function() {
        const self = this;
        
        let fileInput = document.getElementById('hidden-file-input');
        if (!fileInput) {
            fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.id = 'hidden-file-input';
            fileInput.multiple = true;
            fileInput.style.display = 'none';
            document.body.appendChild(fileInput);
        }

        $('#upload-attachment-btn').off('click').on('click', function() {
            fileInput.click();
        });

        $(fileInput).off('change').on('change', async function(e) {
            const files = e.target.files;
            if (files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    await self.addAttachment(files[i]);
                }
            }
            fileInput.value = '';
        });
        
        if (self.draft.current) {
            self.loadDraftAttachments();
        }
    },

    // 添加附件
    addAttachment: async function(file) {
        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
            layui.layer.msg('文件大小不能超过10MB');
            return;
        }

        if (this.draft.current) {
            const loadingIndex = layui.layer.load(1, { shade: 0.1 });
            try {
                const formData = new FormData();
                formData.append('file', file);
                
                const response = await Api.apiRequest(
                    `/upload?type=draft&account_id=${EmailModule.cache.currentAccount}&id=${this.draft.current}`,
                    {
                        method: 'POST',
                        body: formData,
                        isFormData: true
                    }
                );
                
                layui.layer.close(loadingIndex);
                
                this.draft.attachments.push({
                    filename: file.name,
                    size: file.size,
                    uploaded: true
                });
            } catch (error) {
                layui.layer.close(loadingIndex);
                console.error('上传附件失败:', error);
                layui.layer.msg('上传附件失败');
                return;
            }
        } else {
            this.draft.attachments.push(file);
        }

        this.renderAttachmentList();
        this.draft.contentChanged = true;
    },

    // 加载草稿附件
    loadDraftAttachments: async function() {
        if (!this.draft.current) return;
        
        try {
            const response = await Api.apiRequest(
                `/email-accounts/${EmailModule.cache.currentAccount}/drafts/${this.draft.current}/attachments`
            );
            
            if (response && response.length > 0) {
                this.draft.attachments = response.map(att => ({
                    filename: att.filename,
                    size: att.size,
                    uploaded: true
                }));
                this.renderAttachmentList();
            }
        } catch (error) {
            console.error('加载草稿附件失败:', error);
        }
    },

    // 渲染附件列表
    renderAttachmentList: function() {
        $('#attachment-list').empty();
        
        this.draft.attachments.forEach((item, idx) => {
            const filename = item.filename || item.name;
            const size = item.size;
            
            const attachmentItem = $(`
                <div class="attachment-upload-item" data-index="${idx}">
                    <i class="layui-icon layui-icon-file attachment-icon"></i>
                    <div class="attachment-info">
                        <div class="attachment-name">${escapeHtml(filename)}</div>
                        <div class="attachment-size">${formatFileSize(size)}</div>
                    </div>
                    <i class="layui-icon layui-icon-close attachment-remove"></i>
                </div>
            `);

            attachmentItem.find('.attachment-remove').on('click', () => {
                this.removeAttachment(idx);
            });

            $('#attachment-list').append(attachmentItem);
        });
    },

    // 移除附件
    removeAttachment: function(index) {
        this.draft.attachments.splice(index, 1);
        this.renderAttachmentList();
    },

    // 检查内容是否变化
    checkContentChanged: function() {
        const form = $('#compose-email-modal form');
        const currentContent = {
            to: form.find('#compose-to').val(),
            cc: form.find('#compose-cc').val(),
            subject: form.find('#compose-subject').val(),
            body: editor ? editor.txt.html() : ''
        };

        const changed = 
            currentContent.to !== this.draft.lastContent.to ||
            currentContent.cc !== this.draft.lastContent.cc ||
            currentContent.subject !== this.draft.lastContent.subject ||
            currentContent.body !== this.draft.lastContent.body;

        this.draft.contentChanged = changed;
    },

    // 内容变动时立即保存草稿
    saveDraftAuto: async function() {
        this.checkContentChanged();
        
        if (this.draft.contentChanged) {
            await this.performDraftSave('内容变动自动保存');
        }
    },

    // 定时保存草稿
    saveDraftPeriodically: async function() {
        if (!this.draft.lastSaveTime) {
            this.draft.lastSaveTime = new Date();
        }
        
        const timeSinceLastSave = Date.now() - this.draft.lastSaveTime.getTime();
        
        if (timeSinceLastSave >= 10000) {
            await this.performDraftSave('定时保存');
        }
    },

    // 执行草稿保存
    performDraftSave: async function(saveType) {
        const form = $('#compose-email-modal form');
        const to = form.find('#compose-to').val();
        const cc = form.find('#compose-cc').val();
        const subject = form.find('#compose-subject').val();
        const body = editor.txt.html();

        if (!this.draft.current && !to) {
            return;
        }

        const draftData = {
            id: this.draft.current,
            recipients: to,
            cc: cc,
            subject: subject,
            body: body
        };

        try {
            const response = await Api.apiRequest(`/email-accounts/${EmailModule.cache.currentAccount}/drafts`, {
                method: 'POST',
                body: JSON.stringify(draftData)
            });
            
            if (response && response.id) {
                this.draft.current = response.id;
                this.draft.lastSaveTime = new Date();
                
                this.draft.lastContent = {
                    to: to,
                    cc: cc,
                    subject: subject,
                    body: body
                };
                
                this.draft.contentChanged = false;
                this.updateDraftSaveStatus();
            }
        } catch (error) {
            console.error(`${saveType}草稿失败:`, error);
        }
    },

    // 更新草稿保存状态显示
    updateDraftSaveStatus: function() {
        if (this.draft.lastSaveTime) {
            const timeAgo = formatTimeAgo(this.draft.lastSaveTime);
            const statusText = `已于 ${timeAgo} 保存`;
            $('#editor-save-status').text(statusText);
        } else {
            $('#editor-save-status').text('');
        }
    },

    // 发送邮件
    sendEmail: async function(data) {
        const loadingIndex = layui.layer.load(1, { shade: 0.3 });
        
        try {
            const formData = new FormData();
            formData.append('to', data.to);
            if (data.cc) formData.append('cc', data.cc);
            formData.append('subject', data.subject);
            formData.append('body', data.body);
            if (data.draft_id) formData.append('draft_id', data.draft_id);

            // 添加新上传的附件
            this.draft.attachments.forEach((item) => {
                if (item instanceof File) {
                    formData.append('attachments', item);
                }
            });

            const token = localStorage.getItem('token');
            const response = await fetch(`${Api.config.apiBaseUrl}/email-accounts/${EmailModule.cache.currentAccount}/emails/send`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            });

            const result = await response.json();
            if (!result.success) {
                throw new Error(result.msg || '发送失败');
            }

            layui.layer.close(loadingIndex);
            layui.layer.msg('发送成功');
            
            if (this.draft.saveInterval) {
                clearInterval(this.draft.saveInterval);
                this.draft.saveInterval = null;
            }
            
            this.draft.attachments = [];
            
            if (EmailModule.cache.currentFolder === 'Drafts') {
                EmailListManager.reloadEmailList();
            }
        } catch (error) {
            layui.layer.close(loadingIndex);
            console.error('发送邮件失败:', error);
            layui.layer.msg('发送失败: ' + error.message);
        }
    },

    // 初始化邮箱徽标输入组件
    initEmailTagsInput: function(fieldId, initialValue = '') {
        const containerId = `${fieldId}-container`;
        const inputId = `${fieldId}-input`;
        
        const container = $(`#${containerId}`);
        const input = $(`#${inputId}`);
        
        if (!container.length || !input.length) {
            console.error(`邮箱徽标输入组件初始化失败: 找不到元素 ${containerId} 或 ${inputId}`);
            return;
        }
        
        container.find('.email-tag').remove();
        
        if (initialValue) {
            const emails = initialValue.split(',').map(e => e.trim()).filter(e => e);
            emails.forEach(email => {
                this.addEmailTag(fieldId, email);
            });
        }
        
        input.off('keydown').on('keydown', (e) => {
            if (e.key === 'Enter' || e.keyCode === 13) {
                e.preventDefault();
                const email = input.val().trim();
                if (email) {
                    this.addEmailTag(fieldId, email);
                    input.val('');
                    this.updateHiddenInput(fieldId);
                }
            } else if (e.key === 'Backspace' && input.val() === '') {
                const lastTag = container.find('.email-tag').last();
                if (lastTag.length) {
                    lastTag.remove();
                    this.updateHiddenInput(fieldId);
                }
            }
        });
        
        input.off('blur').on('blur', (e) => {
            const value = input.val().trim();
            if (value) {
                const emails = value.split(/[,;，；\s]+/).filter(e => e.trim());
                emails.forEach(email => {
                    email = email.trim();
                    if (email) {
                        this.addEmailTag(fieldId, email);
                    }
                });
                input.val('');
                this.updateHiddenInput(fieldId);
            }
        });
        
        input.off('input').on('input', (e) => {
            const value = input.val();
            if (value.includes(',') || value.includes(';') || value.includes('，') || value.includes('；') || value.includes(' ')) {
                const emails = value.split(/[,;，；\s]+/).filter(e => e.trim());
                let hasAdded = false;
                emails.forEach(email => {
                    email = email.trim();
                    if (email && this.isValidEmail(email)) {
                        this.addEmailTag(fieldId, email);
                        hasAdded = true;
                    }
                });
                if (hasAdded) {
                    const lastPart = emails[emails.length - 1];
                    if (lastPart && !this.isValidEmail(lastPart)) {
                        input.val(lastPart);
                    } else {
                        input.val('');
                    }
                    this.updateHiddenInput(fieldId);
                }
            }
        });
        
        container.off('click').on('click', () => {
            input.focus();
        });
        
        this.updateHiddenInput(fieldId);
    },

    // 添加邮箱徽标
    addEmailTag: function(fieldId, email) {
        const containerId = `${fieldId}-container`;
        const inputId = `${fieldId}-input`;
        
        const container = $(`#${containerId}`);
        const input = $(`#${inputId}`);
        
        if (!email || !this.isValidEmail(email)) {
            layui.layer.msg('请输入有效的邮箱地址', { icon: 2, time: 1500 });
            return;
        }
        
        const existingTags = container.find('.email-tag');
        let isDuplicate = false;
        existingTags.each(function() {
            if ($(this).find('.email-tag-text').text() === email) {
                isDuplicate = true;
                return false;
            }
        });
        
        if (isDuplicate) {
            layui.layer.msg('该邮箱地址已添加', { icon: 2, time: 1500 });
            return;
        }
        
        const tag = $(`
            <div class="email-tag">
                <span class="email-tag-text">${escapeHtml(email)}</span>
                <span class="email-tag-remove">×</span>
            </div>
        `);
        
        tag.find('.email-tag-remove').on('click', (e) => {
            e.stopPropagation();
            tag.remove();
            this.updateHiddenInput(fieldId);
        });
        
        input.before(tag);
        this.updateHiddenInput(fieldId);
    },

    // 更新隐藏输入框的值
    updateHiddenInput: function(fieldId) {
        const containerId = `${fieldId}-container`;
        const hiddenInputId = fieldId;
        
        const container = $(`#${containerId}`);
        const hiddenInput = $(`#${hiddenInputId}`);
        
        const emails = [];
        container.find('.email-tag-text').each(function() {
            emails.push($(this).text());
        });
        
        hiddenInput.val(emails.join(', '));
        hiddenInput.trigger('change');
    },

    // 验证邮箱地址格式
    isValidEmail: function(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }
};
            